const chatForm = document.getElementById('chatForm');
const promptInput = document.getElementById('promptInput');
const messagesContainer = document.getElementById('messages');
const sendBtn = document.getElementById('sendBtn');
const sendText = document.getElementById('sendText');
const loadingText = document.getElementById('loadingText');
const modelSelect = document.getElementById('modelSelect');

let isGenerating = false;

chatForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const prompt = promptInput.value.trim();
    if (!prompt || isGenerating) return;
    
    isGenerating = true;
    toggleSendButton(true);
    
    // Add user message
    addMessage(prompt, 'user');
    promptInput.value = '';
    
    // Add typing indicator
    const typingDiv = addTypingIndicator();
    
    try {
        const selectedModel = modelSelect.value;
        const response = await fetch('/api/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                prompt: prompt,
                model: selectedModel 
            })
        });
        
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        
        // Remove typing indicator and add AI message
        typingDiv.remove();
        const aiMessageDiv = addMessage('', 'ai');
        
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            
            const chunk = decoder.decode(value);
            aiMessageDiv.textContent += chunk;
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        
    } catch (error) {
        console.error('Error:', error);
        typingDiv.remove();
        const errorDiv = addMessage('抱歉，服务出现错误，请稍后重试。', 'ai');
        errorDiv.style.color = 'red';
    } finally {
        isGenerating = false;
        toggleSendButton(false);
    }
});

function addMessage(content, type) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}-message`;
    messageDiv.textContent = content;
    messagesContainer.appendChild(messageDiv);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
    return messageDiv;
}

function addTypingIndicator() {
    const typingDiv = document.createElement('div');
    typingDiv.className = 'typing-indicator';
    typingDiv.textContent = '🤔 AI正在思考中...';
    messagesContainer.appendChild(typingDiv);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
    return typingDiv;
}

function toggleSendButton(loading) {
    sendBtn.disabled = loading;
    if (loading) {
        sendText.style.display = 'none';
        loadingText.style.display = 'inline';
    } else {
        sendText.style.display = 'inline';
        loadingText.style.display = 'none';
    }
}

// Auto-resize textarea
promptInput.addEventListener('input', function() {
    this.style.height = 'auto';
    this.style.height = (this.scrollHeight) + 'px';
});

// Submit on Ctrl+Enter
promptInput.addEventListener('keydown', function(e) {
    if (e.ctrlKey && e.key === 'Enter') {
        chatForm.dispatchEvent(new Event('submit'));
    }
});

// Load available models on page load
window.addEventListener('load', async () => {
    try {
        const response = await fetch('/api/models');
        const data = await response.json();
        
        // Clear existing options
        modelSelect.innerHTML = '';
        
        // Add available models
        data.models?.forEach(model => {
            const option = document.createElement('option');
            option.value = model.name;
            option.textContent = model.name;
            if (model.name.includes('deepseek-r1:32b')) {
                option.selected = true;
            }
            modelSelect.appendChild(option);
        });
    } catch (error) {
        console.log('Failed to load models, using defaults');
    }
});
